#include "stdafx.h"
#include "Contosrv.h"

#include  <wininet.h>
#include <winnls.h>

#include "constdef.h"

HANDLE		g_hConnection=NULL;

CContosrv::CContosrv(CConfig* config)
{
	m_Config = config;
}

CContosrv::~CContosrv(void)
{
	ReleaseNetEnv();
}

BOOL CContosrv::InitNetEnv()
{
	if( TryConnectInternet(35000,&g_hConnection)!=0 )
	{
		return false;
	}

	return true;
}

void CContosrv::ReleaseNetEnv()
{
	DisconnectInternet();
}

int CContosrv::GetUserList(char* userName)
{
#ifdef _GET_FILE_BY_URL_

 	TCHAR urlListFile[MAX_PATH] = {0};
	TCHAR wUserName[MAX_PATH] = {0};
	MultiByteToWideChar(CP_ACP, 0, userName, -1, wUserName, MAX_PATH);
	if(m_Config)
 		swprintf(urlListFile,L"http://%S%S/%s/%S",m_Config->m_ClientInfo.srvIP,A_URL_DATA,wUserName,A_USERLISTFILENAME);
	else
		swprintf(urlListFile,L"http://%S%S/%s/%S",A_SRVIP,A_URL_DATA,wUserName,A_USERLISTFILENAME);

 	return DownloadFileByUrl(urlListFile,A_TEMPUSERLIST);

#else

	if(m_Config)
	{
		return DownloadFile(m_Config->m_ClientInfo.srvIP,A_TEMPUSERLIST,CMD_GETUSERLIST,userName);
	}
	else
	{
		return DownloadFile(A_SRVIP,A_TEMPUSERLIST,CMD_GETUSERLIST,userName);
	}

#endif
}	

int CContosrv::GetMediaList(char* userName)
{
#ifdef _GET_FILE_BY_URL_

	TCHAR urlListFile[MAX_PATH] = {0};
	TCHAR wUserName[MAX_PATH] = {0};
	MultiByteToWideChar(CP_ACP, 0, userName, -1, wUserName, MAX_PATH);

	if(m_Config)
		swprintf(urlListFile,L"http://%S%S/%s/%S",m_Config->m_ClientInfo.srvIP,A_URL_DATA,wUserName,A_MEDIALISTFILENAME);
	else
		swprintf(urlListFile,L"http://%S%S/%s/%S",A_SRVIP,A_URL_DATA,wUserName,A_MEDIALISTFILENAME);
	return DownloadFileByUrl(urlListFile,A_TEMPMEDIALIST);

#else

	if(m_Config)
	{
		return DownloadFile(m_Config->m_ClientInfo.srvIP,A_TEMPMEDIALIST,CMD_GETMEDIALIST,userName);
	}
	else
	{
		return DownloadFile(A_SRVIP,A_TEMPMEDIALIST,CMD_GETMEDIALIST,userName);
	}

#endif
}

int CContosrv::GetMediaFile(char* userName, char* filename, char* tagFile)
{
#ifdef _GET_FILE_BY_URL_	

	TCHAR urlListFile[MAX_PATH] = {0};
	TCHAR wUserName[MAX_PATH] = {0};
	TCHAR wFileName[MAX_PATH] = {0};
	MultiByteToWideChar(CP_ACP, 0, userName, -1, wUserName, MAX_PATH);
	MultiByteToWideChar(CP_ACP, 0, filename, -1, wFileName, MAX_PATH);

	if(m_Config)
		swprintf(urlListFile,L"http://%S%S/%s/%s",m_Config->m_ClientInfo.srvIP,A_URL_DATA,wUserName,wFileName);
	else
		swprintf(urlListFile,L"http://%S%S/%s/%s",A_SRVIP,A_URL_DATA,wUserName,wFileName);
	return DownloadFileByUrl(urlListFile,tagFile);	

#else
	if(m_Config)
		return DownloadFile(m_Config->m_ClientInfo.srvIP,tagFile,CMD_GETMEDIAFILE,userName,filename);
	else
		return DownloadFile(A_SRVIP,tagFile,CMD_GETMEDIAFILE,userName,filename);
#endif
}

BOOL CContosrv::UploadMediaFile(char* filePathName,char* userName,char* fileName)
{
	if(m_Config)
		return UploadFile(m_Config->m_ClientInfo.srvIP,INTERNET_DEFAULT_HTTP_PORT,filePathName,CMD_UPLOADMEDIAFILE,userName,fileName);
	else
		return UploadFile(A_SRVIP,INTERNET_DEFAULT_HTTP_PORT,filePathName,CMD_UPLOADMEDIAFILE,userName,fileName);
}

BOOL CContosrv::UploadFile(char* ip, int port,char* upFile,int cmd,char* para1,char* para2) 
{ 
	if(!InitNetEnv()) return false;

	BOOL bReturn = FALSE;

	HANDLE hFile = NULL;
	HINTERNET hSession=NULL, hConnect=NULL, hRequest=NULL; 
	TCHAR srvURL[256] = {0};//L"/web/mshare/upload_file_ex.php?username=John&filename=test1.txt";
	TCHAR action[20] = L"POST";

	switch (cmd)
	{
	case CMD_UPLOADMEDIAFILE:
		{
		swprintf(srvURL,L"%S/%S?username=%S&filename=%S",A_SRVURL,A_URL_UPLOADMEDIAFILE,para1,para2);
		}break;
	default: 
		return false;
	}

	INTERNET_BUFFERS BufferIn = {0}; 
	DWORD dwBytesRead; 
	DWORD dwBytesWritten; 
	BYTE pBuffer[1024]; // Read from file in 1K chunks 
	BOOL bRead, bRet; 
	DWORD sum = 0; 
	hSession = InternetOpen(TEXT("CeHttp"),INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0); 
	if(!hSession)
	{
		printf("Failed to open internet handle: %lu\n", GetLastError ()); 
		return FALSE;
	}

	//hConnect = InternetConnect(hSession,TEXT("59.108.23.204"), INTERNET_DEFAULT_HTTP_PORT, 
	//	NULL,NULL,INTERNET_SERVICE_HTTP,INTERNET_FLAG_NO_CACHE_WRITE,NULL); 
	TCHAR wstIP[128] = {0};
	swprintf(wstIP,L"%S",ip);
	hConnect = InternetConnect(hSession,wstIP, port, NULL,NULL,INTERNET_SERVICE_HTTP,NULL,NULL); 
	if(!hConnect)
	{
		printf("Failed to internet connect handle: %lu\n", GetLastError ()); 
		goto exit;
	}



	BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); 

	hRequest = HttpOpenRequest (hConnect, action, srvURL, NULL, NULL, NULL,  0, 0); 
	if (!hRequest) 
	{ 
		printf("Failed to open request handle: %lu\n", GetLastError ()); 
		goto exit;
	} 

	TCHAR wstUpfile[256] = {0};
	swprintf(wstUpfile,L"%S",upFile);
	hFile = CreateFile (wstUpfile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 
	if (hFile == INVALID_HANDLE_VALUE) 
	{ 
		printf("\nFailed to open local file %s.", upFile); 
		goto exit;
	} 

	BufferIn.dwBufferTotal = GetFileSize (hFile, NULL); 
	printf ("File size is %d\n", BufferIn.dwBufferTotal ); 

	if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, HSR_INITIATE, 0)) 
	{ 
		int i = GetLastError();
		printf( "Error on HttpSendRequestEx %lu\n",GetLastError() ); 
		goto exit;
	} 


	do 
	{ 
		if  (!(bRead = ReadFile (hFile, pBuffer, sizeof(pBuffer), 
			&dwBytesRead, NULL))) 
		{ 
			printf ("\nReadFile failed on buffer %lu.",GetLastError()); 
			break; 
		} 
		if (!(bRet=InternetWriteFile( hRequest, pBuffer, dwBytesRead, 
			&dwBytesWritten))) 
		{ 
			printf ("\nInternetWriteFile failed %lu", GetLastError()); 
			break; 
		} 
		sum += dwBytesWritten; 
	} 
	while (dwBytesRead == sizeof(pBuffer)) ; 

	printf ("\nActual written bytes: %d\n", sum); 

	if(!HttpEndRequest(hRequest, NULL, 0, 0)) 
	{ 
		printf( "Error on HttpEndRequest %lu \n", GetLastError()); 
		goto exit;
	} 

	bReturn = true;

exit:
	if(hFile)
	{
		CloseHandle (hFile); 
	}

	if(hRequest)
	{
		InternetCloseHandle(hRequest);
	}

	if(hConnect)
	{
		InternetCloseHandle(hConnect);
	}

	if(hSession)
	{
		InternetCloseHandle(hSession);
	}

	ReleaseNetEnv();

	return bReturn; 
}


int CContosrv::DownloadFile(char* szServer,char* szFileName,int cmd,char* para1,char* para2)
{
	if(!InitNetEnv()) return false;

	int bReturn = 0;

	FILE * pFile = NULL;
	HINTERNET hOpen = NULL, 
		hConnect = NULL, 
		hRequest = NULL;

	DWORD dwSize = 0;
	DWORD dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE; 

	TCHAR szErrMsg[200];
	char *lpBufferA,*lpHeadersA;
	TCHAR *lpBufferW,*lpHeadersW;
	//LPTSTR AcceptTypes[] = {TEXT("*/*"), NULL}; 
	const TCHAR*	pAcceptType[] = {L"*/*",NULL};

	TCHAR srvURL[256] = {0};//L"/web/mshare/getMedialist.php?username=vic";
	TCHAR action[20] = L"GET";

	TCHAR wpara1[MAX_PATH] = {0};
	TCHAR wpara2[MAX_PATH] = {0};
	MultiByteToWideChar(CP_ACP, 0, para1, -1, wpara1, MAX_PATH);
	MultiByteToWideChar(CP_ACP, 0, para2, -1, wpara2, MAX_PATH);

	switch (cmd)
	{
	case CMD_GETUSERLIST:
		{
		swprintf(srvURL,L"%S/%S?username=%s",A_SRVURL,A_URL_GETUSERLIST,wpara1);	
		}break;
	case CMD_GETMEDIALIST:
		{
		swprintf(srvURL,L"%S/%S?username=%s",A_SRVURL,A_URL_GETMEDIALIST,wpara1);	
		}break;
	case CMD_GETMEDIAFILE:
		{
		swprintf(srvURL,L"%S/%S?username=%s&filename=%s",A_SRVURL,A_URL_GETMEDIAFILE,wpara1,wpara2);	
		}break;
	default: 
		break;
	}

	STLOG_WRITE(srvURL);

	// Initialize the use of the Windows CE Internet functions.
	//hOpen = InternetOpen (TEXT("CeHttp"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, 0, 0);
	hOpen = InternetOpen (TEXT("CeHttp"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

	if (!hOpen)
	{
		swprintf (szErrMsg, TEXT("%s: %x"), TEXT("InternetOpen Error"), GetLastError());
		STLOG_WRITE(szErrMsg);
		return FALSE;
	}
	STLOG_WRITE(L"InternetOpen");

	TCHAR wtsSrv[128] = {0};	
	swprintf (wtsSrv, L"%S",szServer);
	// Open an HTTP session for a specified site by using lpszServer. 
	if (!(hConnect = InternetConnect (hOpen, 
		wtsSrv, 
		INTERNET_DEFAULT_HTTP_PORT, 
		NULL, NULL, 
		INTERNET_SERVICE_HTTP, 
		NULL, NULL)))
	{
		swprintf (szErrMsg, TEXT("%s: %x"), TEXT("InternetConnect Error"),GetLastError());
		STLOG_WRITE(szErrMsg);
		goto exit;
	}
	STLOG_WRITE(L"InternetConnect");

	// Open an HTTP request handle. 
	if (!(hRequest = HttpOpenRequest (hConnect, 
		TEXT("GET"), 
		srvURL,
		NULL, 
		NULL, 
		pAcceptType,//(LPCTSTR*)AcceptTypes, 
		dwFlags, 0)))
	{
		swprintf (szErrMsg, TEXT("%s: %x"), TEXT("HttpOpenRequest Error"), GetLastError());
		STLOG_WRITE(szErrMsg);
		goto exit;
	}

	STLOG_WRITE(L"HttpOpenRequest");

	//DWORD dwTimeOut = 55*1000;
	//InternetSetOption(hRequest, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD));
	//InternetSetOption(hRequest, INTERNET_OPTION_DATA_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD));

	// Send a request to the HTTP server. 
	if (!HttpSendRequest (hRequest, NULL, 0, NULL, 0))
	{
		swprintf (szErrMsg, TEXT("%s: %x"), TEXT("HttpSendRequest Error"),GetLastError());
		STLOG_WRITE(szErrMsg);
		goto exit;
	}

	STLOG_WRITE(L"HttpSendRequest");
	//ERROR_INTERNET_NAME_NOT_RESOLVED 

	unsigned char szTemp1[4];
	unsigned int dwRet = 4;

	HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE, szTemp1, (LPDWORD)&dwRet,NULL);
	DWORD dwStatCode = 0;
	dwStatCode = atol((const char*)szTemp1) ;
	if(dwStatCode!=200)
	{
		bReturn = false;	
		//goto exit;
	}

	// Call HttpQueryInfo to find out the size of the headers.
	HttpQueryInfo(hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, NULL, &dwSize, NULL);

	STLOG_WRITE(L"HttpQueryInfo");
	// Allocate a block of memory for lpHeadersA.
	lpHeadersA = new CHAR [dwSize];
	if(!lpHeadersA)
	{
		delete[] lpHeadersA;
		goto exit;
	}

	// Call HttpQueryInfo again to get the headers.
	if (!HttpQueryInfo(hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, (LPVOID) lpHeadersA, &dwSize, NULL))
	{
		swprintf (szErrMsg, TEXT("%s: %x"), TEXT("HttpQueryInfo"),GetLastError());
		STLOG_WRITE(szErrMsg);
		goto exit;
	}

	// Terminate headers with NULL.
	lpHeadersA [dwSize] = '\0';

	// Get the required size of the buffer that receives the Unicode 
	// string. 
	dwSize = MultiByteToWideChar (CP_ACP, 0, lpHeadersA, -1, NULL, 0);

	// Allocate a block of memory for lpHeadersW.
	lpHeadersW = new TCHAR [dwSize];
	lpHeadersW = new TCHAR [dwSize];
	//if memory allocation fails, then free the block of memory.
	if(!lpHeadersW)
	{
		delete[] lpHeadersW;
		goto exit;
	}

	// Convert headers from ASCII to Unicode.
	MultiByteToWideChar (CP_ACP, 0, lpHeadersA, -1, lpHeadersW, dwSize);  

	// Free the blocks of memory.
	delete[] lpHeadersA;
	delete[] lpHeadersW;

	// Allocate a block of memory for lpHeadersW.
	const int KBUFSIZE = 3200;
	DWORD bufSize = KBUFSIZE+1;
	lpBufferA = new CHAR [bufSize];
	//if memory allocation fails, then free the block of memory.
	if(!lpBufferA)
	{
		delete[] lpBufferA;
		goto exit;
	}

	TCHAR wszFileName[256] = {0};
	swprintf(wszFileName,L"%S",szFileName);
	if  ( !(pFile = fopen (szFileName, "wb" ) ) )
	{
		//printf("Failed to write file");
		STLOG_WRITE("Failed to write file");
		goto exit;
	}

	STLOG_WRITE(L"Open tag file");

	int i = 0;
	do
	{
		memset(lpBufferA,0,bufSize);
		if (!InternetReadFile (hRequest, (LPVOID)lpBufferA, KBUFSIZE, &dwSize))
		{
			swprintf(szErrMsg, TEXT("%s: %x"), TEXT("InternetReadFile Error"),GetLastError());
			STLOG_WRITE(szErrMsg);
			goto exit;
		}
		if(i==0)
		{
			char tmp[12] = {0};
			strncpy(tmp,lpBufferA,11);
			if(strcmp(tmp,"MSHARE:NULL") == 0)
			{
				bReturn = 404;
				goto exit;
			}
			i++;
		}

		if (dwSize != 0)    
		{
			// Terminate headers with NULL.
			//lpBufferA [dwSize] = '\0';                 

			// Get the required size of the buffer which receives the Unicode
			// string. 
			//dwSize = MultiByteToWideChar (CP_ACP, 0, lpBufferA, -1, NULL, 0);

			// Allocate a block of memory for lpBufferW.
			//lpBufferW = new TCHAR [dwSize];

			// Convert the buffer from ASCII to Unicode.
			//MultiByteToWideChar (CP_ACP, 0, lpBufferA, -1, lpBufferW, dwSize);  

			// Free the block of memory.
			//delete[] lpBufferW;  

			fwrite(lpBufferA, sizeof (char), dwSize , pFile);

			bReturn = 200;
		}    
	} while (dwSize);

	// Free the block of memory.
	delete[] lpBufferA;  

	STLOG_WRITE(L"WriteFile");

exit:
	if(pFile)
	{
		fflush (pFile);
		fclose (pFile);
	}

	if (hRequest)
	{
		if (!InternetCloseHandle (hRequest))
			swprintf (szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
	}

	if (hConnect)
	{
		if (!InternetCloseHandle (hConnect))
			swprintf (szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
	}

	// Close the Internet handles.
	if (hOpen)
	{
		if (!InternetCloseHandle (hOpen))
			swprintf (szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
	}

	//printf(szErrMsg);
	ReleaseNetEnv();

	return bReturn;
}


int CContosrv::DownloadFileByUrl (TCHAR *szUrl,CHAR *szFileName)
{
	if(!InitNetEnv()) return false;

	int retVal = 404;
	DWORD dwSize;
	TCHAR   szHead[] = L"Accept: */*\r\n\r\n";
	VOID * szTemp[25];
	HINTERNET hOpen = NULL;
	HINTERNET  hConnect = NULL;
	FILE * pFile = NULL;

	//hOpen = InternetOpen(L"client2.exe",INTERNET_OPEN_TYPE_PROXY,L"10.0.0.172:80", NULL, 0);
	
	hOpen = InternetOpen(TEXT("test"),INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0); 

	if ( !(hConnect = InternetOpenUrl ( hOpen, szUrl, szHead,
		_tcslen (szHead), INTERNET_FLAG_DONT_CACHE, 0)))
	{
		STLOG_WRITE("Failed to OpenUrl err=%d",GetLastError());
		retVal = false;	
		goto exit;
	}

	unsigned char szTemp1[4];
	unsigned int dwRet = 4;

	HttpQueryInfoA(hConnect, HTTP_QUERY_STATUS_CODE, szTemp1, (LPDWORD)&dwRet,NULL);
	DWORD dwStatCode = 0;
	dwStatCode = atol((const char*)szTemp1) ;
	if(dwStatCode!=200)
	{
		retVal = dwStatCode;	
		goto exit;
	}

	if  ( !(pFile = fopen (szFileName, "wb" ) ) )
	{
		STLOG_WRITE("Failed to write file %d",GetLastError());
		retVal = 1;	
		goto exit;
	}
	do
	{
		int packSize = 25;
		// Keep coping in 25 bytes chunks, while file has any data left.
		// Note: bigger buffer will greatly improve performance.
		if (!InternetReadFile (hConnect, szTemp, packSize,  &dwSize) )
		{
			STLOG_WRITE("Failed to read file from server");
			goto exit;
		}
		if (!dwSize)
		{
			break;  // Condition of dwSize=0 indicate EOF. Stop.
		}
		else
		{
			fwrite(szTemp, sizeof (char), dwSize , pFile);
			retVal = 200;	
		}
	}   // do
	while (TRUE);

exit:
	if(pFile)
	{
		fflush (pFile);
		fclose (pFile);
	}
	
	if(hConnect)
	{
		InternetCloseHandle(hConnect);
	}

	if(hOpen)
	{
		InternetCloseHandle(hOpen);
	}

	ReleaseNetEnv();

	return retVal;
}


void CContosrv::DisconnectInternet()
{
	if(m_hConnection)
	{
		ConnMgrReleaseConnection(m_hConnection, FALSE);
		m_hConnection = NULL;
	}
}

HRESULT CContosrv::TryConnectInternet(DWORD dwTimeout, HANDLE* phConnection)
{
	CONNMGR_CONNECTIONINFO		ConnInfo;
	//	CONNMGR_DESTINATION_INFO	DestInfo;
	int i = 0;
	HRESULT hResult = -1;
	DWORD dwStatus = 0;

	//	for(i = 0; SUCCEEDED(ConnMgrEnumDestinations(i, &DestInfo)); i++)
	//	{
	//		ZeroMemory(&ConnInfo, sizeof(ConnInfo));
	//		ConnInfo.cbSize = sizeof(ConnInfo);
	//		ConnInfo.dwParams = CONNMGR_PARAM_GUIDDESTNET;
	//		ConnInfo.dwPriority = CONNMGR_PRIORITY_USERBACKGROUND;
	//		ConnInfo.guidDestNet = m_gNetwork;//DestInfo.guid;
	//		ConnInfo.dwFlags=CONNMGR_FLAG_PROXY_HTTP;
	//
	//		hResult = ConnMgrEstablishConnectionSync(&ConnInfo, &m_hConnection, dwTimeout, &dwStatus);
	//		if(SUCCEEDED(hResult) && (dwStatus == CONNMGR_STATUS_CONNECTED))
	//		{
	//			hConnection = m_hConnection;
	// 			return hResult;
	//		}
	// 	}
	// 	return -1;

	GUID    m_gNetwork;     // the GUID for the network we are connecting to.

	ConnMgrMapURL(L"http://www.fortinet.com", &m_gNetwork, 0);

	ZeroMemory(&ConnInfo, sizeof(ConnInfo));
	ConnInfo.cbSize = sizeof(ConnInfo);
	ConnInfo.dwParams = CONNMGR_PARAM_GUIDDESTNET;
	ConnInfo.dwPriority = CONNMGR_PRIORITY_USERBACKGROUND;
	ConnInfo.guidDestNet = m_gNetwork;//DestInfo.guid;
	ConnInfo.dwFlags=CONNMGR_FLAG_PROXY_HTTP;

	//IID_DestNetInternet

	hResult = ConnMgrEstablishConnectionSync(&ConnInfo, &m_hConnection, dwTimeout, &dwStatus);
	if(SUCCEEDED(hResult) && (dwStatus == CONNMGR_STATUS_CONNECTED))
	{
		if( phConnection!=NULL )
		{
			*phConnection = m_hConnection;
		}
		return hResult;
	}

	return -1;
}


BOOL CContosrv::GetProxyServer( HANDLE hConnection, char* pszProxyServer )
{
	PROXY_CONFIG	proxy = {0};
	HRESULT			hr = -1;
	const GUID		IID_ConnPrv_IProxyExtension = { 0xaf96b0bd, 0xa481, 0x482c, { 0xa0, 0x94, 0xa8, 0x44, 0x87, 0x67, 0xa0, 0xc0 } };

	proxy.dwType = CONNMGR_FLAG_PROXY_HTTP;
	hr = ConnMgrProviderMessage( hConnection, &IID_ConnPrv_IProxyExtension, NULL, 0, 0, (PBYTE)&proxy, sizeof(proxy)); 
	if( SUCCEEDED(hr) )
	{
		BSTR_TO_STRING(proxy.szProxyServer,pszProxyServer,CMPROXY_PROXYSERVER_MAXSIZE);
		return TRUE;
	}

	return FALSE;
}

BOOL CContosrv::GetInternetFile (LPTSTR lpszServer, LPTSTR lpszProxyServer, bool bProxy,bool bOpenURL)
{
	STLOG_WRITE(L"InitNetEnv");
	if(!InitNetEnv()) return false;

	BOOL bReturn = FALSE;

	HINTERNET hOpen = NULL, 
		hConnect = NULL, 
		hRequest = NULL;

	DWORD dwSize = 0, 
		dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE; 

	TCHAR szErrMsg[200];

	char *lpBufferA,
		*lpHeadersA;

	TCHAR *lpBufferW,
		*lpHeadersW;

	LPTSTR AcceptTypes[2] = {TEXT("*/*"), NULL}; 


	// Initialize the use of the Windows CE Internet functions.
	if (bProxy)
	{
		hOpen = InternetOpen (TEXT("test"), INTERNET_OPEN_TYPE_PROXY, 
			lpszProxyServer, 0, 0);
	}
	else
	{
		//INTERNET_OPEN_TYPE_DIRECT
		//hOpen = InternetOpen (TEXT("CeHttp"), INTERNET_OPEN_TYPE_PRECONFIG,
		hOpen = InternetOpen (TEXT("test"), INTERNET_OPEN_TYPE_DIRECT,
			NULL, 0, 0);
	}

	if (!hOpen)
	{
		wsprintf (szErrMsg, TEXT("%s: %x"), TEXT("InternetOpen Error"), 
			GetLastError());
		STLOG_WRITE(szErrMsg);
		return FALSE;
	}

	STLOG_WRITE(L"InternetOpen");

	if (bOpenURL)
	{
		TCHAR   szHead[] = L"Accept: */*\r\n\r\n";
		if ( !(hRequest = InternetOpenUrl ( hOpen, lpszServer, szHead,
			_tcslen (szHead), INTERNET_FLAG_DONT_CACHE, 0)))

		//if (!(hRequest = InternetOpenUrl (hOpen, lpszServer, NULL, 0, 
		//	INTERNET_FLAG_RELOAD, 0)))
		{
			wsprintf (szErrMsg, TEXT("%s: %x"), TEXT("InternetOpenUrl Error"),
				GetLastError());
			STLOG_WRITE(szErrMsg);
			goto exit;

		}
		STLOG_WRITE(L"InternetOpenUrl");
	}
	else
	{
		// Open an HTTP session for a specified site by using lpszServer. 
		if (!(hConnect = InternetConnect (hOpen, 
			lpszServer, 
			INTERNET_INVALID_PORT_NUMBER, 
			NULL, NULL, 
			INTERNET_SERVICE_HTTP, 
			0, 0)))
		{
			wsprintf (szErrMsg, TEXT("%s: %x"), TEXT("InternetConnect Error"),
				GetLastError());
			STLOG_WRITE(szErrMsg);
			goto exit;
		}

		STLOG_WRITE(L"InternetConnect");

		// Open an HTTP request handle. 
		if (!(hRequest = HttpOpenRequest (hConnect, 
			TEXT("GET"), 
			NULL, 
			HTTP_VERSION, 
			NULL, 
			(LPCTSTR*)AcceptTypes, 
			dwFlags, 0)))
		{
			wsprintf (szErrMsg, TEXT("%s: %x"), TEXT("HttpOpenRequest Error"),
				GetLastError());
			STLOG_WRITE(szErrMsg);
			goto exit;
		}

		STLOG_WRITE(L"HttpOpenRequest");

		// Send a request to the HTTP server. 
		if (!HttpSendRequest (hRequest, NULL, 0, NULL, 0))
		{
			wsprintf (szErrMsg, TEXT("%s: %x"), TEXT("HttpSendRequest Error"),
				GetLastError());
			STLOG_WRITE(szErrMsg);
			goto exit;
		}

		STLOG_WRITE(L"HttpSendRequest");
	}

	// Call HttpQueryInfoAto find out the size of the headers.
	HttpQueryInfoA(hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, NULL, &dwSize,
		NULL);

	STLOG_WRITE(L"HttpQueryInfoA");

	// Allocate a block of memory for lpHeadersA.
	lpHeadersA = new CHAR [dwSize];
	//if memory allocation fails, then free the block of memory.
	if(!lpHeadersA)
	{
		delete[] lpHeadersA;
		goto exit;
	}
	// Call HttpQueryInfoA again to get the headers.
	if (!HttpQueryInfoA(hRequest, 
		HTTP_QUERY_RAW_HEADERS_CRLF, 
		(LPVOID) lpHeadersA, &dwSize, NULL))
	{
		wsprintf (szErrMsg, TEXT("%s: %x"), TEXT("HttpQueryInfo"), 
			GetLastError());
		STLOG_WRITE(szErrMsg);
		goto exit;
	}
	else
	{
	
	}

	// Terminate headers with NULL.
	lpHeadersA [dwSize] = '\0';

	// Get the required size of the buffer that receives the Unicode 
	// string. 
	dwSize = MultiByteToWideChar (CP_ACP, 0, lpHeadersA, -1, NULL, 0);

	// Allocate a block of memory for lpHeadersW.
	lpHeadersW = new TCHAR [dwSize];
	//if memory allocation fails, then free the block of memory.
	if(!lpHeadersW)
	{
		delete[] lpHeadersW;
		goto exit;
	}

	// Convert headers from ASCII to Unicode.
	MultiByteToWideChar (CP_ACP, 0, lpHeadersA, -1, lpHeadersW, dwSize);  


	// Free the blocks of memory.
	delete[] lpHeadersA;
	delete[] lpHeadersW;

	// Allocate a block of memory for lpHeadersW.
	lpBufferA = new CHAR [32000];
	//if memory allocation fails, then free the block of memory.
	if(!lpBufferA)
	{
		delete[] lpBufferA;
		goto exit;
	}

	do
	{
		if (!InternetReadFile (hRequest, (LPVOID)lpBufferA, 31999, &dwSize))
		{
			wsprintf(szErrMsg, TEXT("%s: %x"), TEXT("InternetReadFile Error"), 
				GetLastError());
			goto exit;
		}

		STLOG_WRITE(L"InternetReadFile %s",lpBufferA);

		if (dwSize != 0)    
		{
			// Terminate headers with NULL.
			lpBufferA [dwSize] = '\0';                 

			// Get the required size of the buffer which receives the Unicode
			// string. 
			dwSize = MultiByteToWideChar (CP_ACP, 0, lpBufferA, -1, NULL, 0);

			// Allocate a block of memory for lpBufferW.
			lpBufferW = new TCHAR [dwSize];
			//if memory allocation fails, then free the block of memory.
			if(!lpBufferW)
			{
				delete[] lpBufferW;
				goto exit;
			}

			// Convert the buffer from ASCII to Unicode.
			MultiByteToWideChar (CP_ACP, 0, lpBufferA, -1, lpBufferW, dwSize);  

			// Free the block of memory.
			delete[] lpBufferW;  
		}    
	} while (dwSize);

	// Free the block of memory.
	delete[] lpBufferA;  

	bReturn = TRUE;

exit:

	// Close the Internet handles.
	if (hOpen)
	{
		if (!InternetCloseHandle (hOpen))
			wsprintf (szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), 
			GetLastError());
	}

	if (hConnect)
	{
		if (!InternetCloseHandle (hConnect))
			wsprintf (szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), 
			GetLastError());
	}

	if (hRequest)
	{
		if (!InternetCloseHandle (hRequest))
			wsprintf (szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), 
			GetLastError());
	}

	return bReturn;
}
